from typing import Annotated
from sqlalchemy.orm import Session
from fastapi import APIRouter, Depends, HTTPException , status, Path
from models import Todos
from database import sessionmaker
from pydantic import BaseModel , Field
from .auth import get_current_user


SessionLocal = sessionmaker


router = APIRouter(
    prefix="/admin",
    tags=["admin"],
)

# 定义获取数据库会话的依赖函数
def get_db():
    # 创建新的数据库会话
    db = SessionLocal()
    try:
        # 使用yield返回数据库会话
        yield db
    finally:
        # 确保在请求结束时关闭数据库会话
        db.close()

# 创建类型注解的数据库依赖项，用于FastAPI的依赖注入系统
db_dependency = Annotated[Session, Depends(get_db)]

user_dependency = Annotated[dict, Depends(get_current_user)]


@router.get("/todo", status_code=status.HTTP_200_OK)
async def read_all(user: user_dependency, db: db_dependency):
    if user is None or user.get("role") != "admin":
        raise HTTPException(status_code=401, detail='Authentication Failed')
    return db.query(Todos).all()

@router.delete("/todo/{todo_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_todo(user: user_dependency, db: db_dependency, todo_id: int = Path(gt=0)):
    if user is None or user.get("role")!= "admin":
        raise HTTPException(status_code=401, detail='Authentication Failed')
    todo_model = db.query(Todos).filter(Todos.id == todo_id).first()
    if todo_model is None:
        raise HTTPException(status_code=404, detail='Todo not found')
    db.query(Todos).filter(Todos.id == todo_id).delete()
    db.commit()